import './style.less';

import * as R from 'ramda';
import * as roleSvc from '@/service/role';

import { Empty, Space, Tree } from 'antd';
import React, {
  forwardRef,
  memo,
  useImperativeHandle,
  useMemo,
  useState,
} from 'react';
import {
  covertTreeData,
  flattenTree,
  unResWrapper,
} from '../../../../../utils/common';

import EnumTag from '../../../../../components/EnumTag';
import { Loading } from '@r-magician/ui';
import ProCard from '@ant-design/pro-card';
import RoleInfo from './RoleInfo';
import SystemList from './SystemList';
import { cls } from './config';
import { getMenuTree } from '../../../../../service/menu';
import { useRequest } from 'ahooks';
import variables from '../../../../../lib/themeVariables';

const makeTree = (res) =>
  covertTreeData(res, (item) => {
    return {
      title: (
        <Space>
          <EnumTag.MenuTag value={item.type} />
          <span>{item.name}</span>
          <span>({item.code})</span>
        </Space>
      ),
      value: item.id,
      key: item.id,
      ...item,
    };
  });

// 授权组件
const Authorization = forwardRef(({ role, editData, onSuccess }, ref) => {
  const [curSystem, setCurSystem] = useState(null);

  const [menuCheckedKeys, setMenuCheckedKeys] = useState(() => {
    return role.menuList.map((item) => {
      return item.id;
    });
  });
  const { loading, data } = useRequest(
    () =>
      unResWrapper(getMenuTree)({
        systemId: curSystem.id,
      }),
    {
      refreshDeps: [curSystem],
      ready: !!curSystem,
    },
  );

  const antdTreeData = useMemo(() => makeTree(data || []), [data]);
  const handleCheck = (e) => {
    setMenuCheckedKeys(e);
  };

  // useMount(() => {
  //   if (editData) {
  //     const ids = editData.menuList.map((item) => {
  //       return item.id;
  //     });
  //     setMenuCheckedKeys(ids);
  //   }
  // });

  useImperativeHandle(
    ref,
    () => {
      return {
        getData: () => ({ menu: menuCheckedKeys.checked }),
      };
    },
    [menuCheckedKeys],
  );

  return (
    <div className={cls()}>
      <RoleInfo role={role} />
      <ProCard
        title="选择系统菜单"
        size="small"
        split="vertical"
        bordered
        headerBordered
      >
        <ProCard
          colSpan="calc(100% / 3)"
          bodyStyle={{
            height: 500,
            overflowX: 'hidden',
            overflowY: 'auto',
            padding: 0,
          }}
        >
          <SystemList
            curSystem={curSystem}
            handleClickItem={(item) => setCurSystem(item)}
            onSuccess={(list) => {
              const first = R.head(list);
              if (first) {
                setCurSystem(first);
              }
            }}
          />
        </ProCard>
        <ProCard>
          {loading ? (
            <Loading />
          ) : antdTreeData.length ? (
            <Tree
              checkStrictly
              checkable
              defaultExpandAll
              checkedKeys={menuCheckedKeys}
              treeData={antdTreeData}
              onCheck={handleCheck}
              height={476}
            />
          ) : (
            <Empty description={`【${curSystem?.name}】还没菜单哦~`} />
          )}
        </ProCard>
      </ProCard>
    </div>
  );
});

export default memo(Authorization);
